//创建元素

class Node{
    constructor(element){
        this.element = element;
        this.next = null;
    }
}

//链表的类

class LinkList{
    constructor(){
        this.head = null;  //链表的首元素
        this.count = 0;    //记录链表的个数
    }

    //push  添加元素
    push(element){
        let node = new Node(element);
        //当前链表是否为空
        if(this.head === null){
            this.head = node;
        }else{
            let current = this.head; //记录首元素
            //查找末尾元素
            while(current.next != null){
                current = current.next;
            }
            //把末尾元素的next指针指向新创建的节点
            current.next = node;
        }
        this.count++;
    }

    //查找目标元素
    getNode(index){//2
        let current = this.head; //保存首元素
        for(let i = 0;i<index;i++){
            current = current.next;
        }
        return current
    }

    //插入
    insert(element,index){ //index:插入的位置
        //边界值的判断
        if(index >= 0 && index <= this.count){
            //插入
            //1.创建一个元素
            let node = new Node(element);
            //是否在开头插入
            if(index === 0){
                //在开头
                if(this.head === null){
                    this.head = node;
                }else{
                    let current = this.head;
                    this.head = node;
                    node.next = current;
                }
            }else{
                //不是在开头
                let prev = this.getNode(index-1);//
                let current = prev.next;
                prev.next = node;
                node.next = current;
            }
            this.count++;
        }else{
            return false
        }
    }
}

let l = new LinkList();

l.push('a');

l.push('b');

l.push('c');

l.insert('d',0);

console.log(l)

//1.周考题  2.模块规范  3.单向链表 